package com.ads.proplan.activity;

import java.io.IOException;
import java.util.Date;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.AlertDialog;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.ads.proplan.R;
import com.ads.proplan.control.CadastroControl;
import com.ads.proplan.db.entity.Usuario;
import com.google.gson.Gson;
import com.googlecode.androidannotations.annotations.Click;
import com.googlecode.androidannotations.annotations.EActivity;
import com.googlecode.androidannotations.annotations.ViewById;


@EActivity(R.layout.activity_cadastre)
public class CadastroActivity extends Activity{

	@ViewById(R.id.cadastr_edit_nome)
	EditText nomeEditText;
		
	@ViewById(R.id.cadastr_edit_email)
	EditText emailEditText;
	
	@ViewById(R.id.cadastr_edit_senha)
	EditText senhaEditText;
	
	@ViewById(R.id.cadastr_edit_confirma)
	EditText confirmarEditText;

	private CadastroControl control;
	
//	private String valueIp = "172.18.9.98";
	private String valueIp = "192.168.0.104";
	
	@Override
	protected void onStart() {
		super.onStart();
		control = CadastroControl.getInstance();
		setupUI(findViewById(R.id.cadastr_layout));
	}
	
	@Click(R.id.cadastr_button_cadastrar)
	public void OnClicButtonCadastrar() {
		if (!nomeEditText.getText().toString().equals("")
				&& !emailEditText.getText().toString().equals("")
				&& !senhaEditText.getText().toString().equals("")) {
			String nome = nomeEditText.getText().toString();
			if(!emailEditText.getText().toString().equals("") && emailEditText.getText().toString().contains("@")){
				String email = emailEditText.getText().toString();
				if (email.split("@")[1].equals("unifor.br")
						|| email.split("@")[1].equals("edu.unifor.br")) {
					if(senhaEditText.getText().toString().length() >= 3){
						if (senhaEditText.getText().toString()
								.equals(confirmarEditText.getText().toString())) {
							String senha = senhaEditText.getText().toString();
							final Usuario usuario = new Usuario();
							usuario.setEmail(email);
							usuario.setNome(nome);
							usuario.setSenha(senha);
							conectar(usuario);
							control.addUsuario(email, nome, senha);
							control.finalizeControl();
							PresentationActivity_.intent(this).start();
							finish();
						} else {
							alerta("Senha errada");
							senhaEditText.setSelected(true);
						}
					}else{
						alerta("Senha curta. Minimo de 3 caracteres");
					}
					
				} else {
					alerta("E-mail errado");
				}
			}else{
				alerta("E-mail incompleto");
			}
		} else {
			//alerta("Preencha todos os campos");
			//TODO Retirar Depois
			control.finalizeControl();
			PresentationActivity_.intent(this).start();
			finish();
		}
	}

	private void conectar(final Usuario usuario) {
		Thread thread = new Thread()
		{
			@Override
			public void run() {
				try {
					setUsuarioWeb(usuario);
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
		    }
		};
		thread.start();
	}
	
	private void alerta(String text) {
		AlertDialog.Builder alt = new AlertDialog.Builder(this);
		alt.setTitle("Erro no Cadastro");
		alt.setMessage(text);
		alt.setPositiveButton("Corrigir", null);
		alt.show();
	}
	
	public static void hideSoftKeyboard(Activity activity) {
	    InputMethodManager inputMethodManager = (InputMethodManager)  activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
	    inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
	}
	
	public void setupUI(View view) {

	    if(!(view instanceof EditText)) {

	        view.setOnTouchListener(new OnTouchListener() {

	            public boolean onTouch(View v, MotionEvent event) {
	            	hideSoftKeyboard(CadastroActivity.this);
	                return false;
	            }

	        });
	    }
	}
	@Override
	public void onBackPressed() {
		MenuCadastroActivity_.intent(this).start();
		finish();
	}
	
	private String gerarToken(){
		Date date = new Date();
		String token = (""+date.getTime()+((int)(Math.random()*10000)));		
		return token;
	}
	
	private boolean setUsuarioWeb(Usuario usuario) throws ClientProtocolException, IOException{
		usuario.setToken(gerarToken());
	
		HttpClient httpclient = new DefaultHttpClient();
		Log.i("GSONSET","antes Url");
        HttpPost httpPost = new HttpPost("http://"+valueIp+":8085/Quiz/login");
        Log.i("GSONSET","depois Url");
        String json = new Gson().toJson(usuario);
        StringEntity se = new StringEntity(json);
        httpPost.setEntity(se);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");
        Log.i("GSONSET","antes executar");
        HttpResponse httpResponse = httpclient.execute(httpPost);
        Log.i("GSONSET","depois de executar");
//        InputStream inputStream = httpResponse.getEntity().getContent();
//        Reader reader = new InputStreamReader(inputStream, "UTF-8");
//        Usuario results = new Gson().fromJson(reader,new TypeToken<Usuario>() {}.getType());
        
        return true;
	}
}
		
